<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use App\Response\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class IndependentPoolUserController extends BaseController
{
    /**
     * @api {Get} /independentPoolUser/poolUserList 用户列表
     * @apiGroup 补充接口-幸运树游戏
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "id": 1,
    "user_id": 547900,
    "add_time": "2021-03-24 17:55:53",
    "expired_time": "2021-03-31 00:00:00",
    "status": 1,
    "total_income": 0,
    "total_cost": 0,
    "total_income_current": 0,
    "total_cost_current": 0,
    "pool_config": "1",
    "user_code": 617040,
    "nickname": "提莫队长呢",
    "head_picture": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/admin_images/5ee1d62377f10.jpeg",
    "pool_config_list": "奖池2"
    }
    ],
    "first_page_url": "http://local.qipaoadmin/independentPoolUser/poolUserList?page=1",
    "from": 1,
    "last_page": 1,
    "last_page_url": "http://local.qipaoadmin/independentPoolUser/poolUserList?page=1",
    "next_page_url": null,
    "path": "http://local.qipaoadmin/independentPoolUser/poolUserList",
    "per_page": 20,
    "prev_page_url": null,
    "to": 1,
    "total": 1
    }
    }
     */
    public function poolUserList()
    {
        $list = app('model_independent_pool_user')->getIndependentPoolUserList();
        return Response::sendData($list);
    }

    /**
     * @api {Post} /independentPoolUser/add 添加用户
     * @apiGroup 补充接口-幸运树游戏
     *
     * @apiParam {Int} user_code 用户编号
     * @apiParam {String} expired_time 过期时间
     * @apiParam {String} pool_config 奖池id，多个用户逗号,连接
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function add(Request $request)
    {
        $userCode = $request->user_code; //用户编号
        $expiredTime = $request->expired_time; //过期时间
        $poolConfig = $request->pool_config; //奖池配置，多个用逗号,连接

        if ($expiredTime <= date('Y-m-d H:i:s')) {
            throw new BasicException(0, '过期时间必须大于当前时间');
        }

        $userId = app('model_user_data')->where('user_code', $userCode)->value('user_id');
        if (!$userId) {
            throw new BasicException(0, '用户不存在');
        }
        $independent_user = app('model_independent_pool_user')->where(['user_id' => $userId])->first();
        if (isset($independent_user->status) && $independent_user->status == 1) {
            throw new BasicException(0, '用户已有特殊独立奖池');
        }
        if (empty($poolConfig)) {
            throw new BasicException(0, '请选择奖池类型');
        }

        DB::beginTransaction();

        $data = [
            'user_id'      => $userId,
            'expired_time' => strtotime($expiredTime),
            'pool_config'  => $poolConfig,
        ];
        if ($independent_user) {
            $data['total_income_current'] = 0;
            $data['total_cost_current'] = 0;
            $data['status'] = 1;
            app('model_independent_pool_user')->where(['user_id' => $userId])->update($data);
        } else {
            $data['add_time'] =  time();
            app('model_independent_pool_user')->insert($data);
        }
        app('model_independent_pool_user')->copyIndependentPool($userId);

        DB::commit();

        return Response::sendData([]);
    }

    /**
     * @api {Put} /independentPoolUser/edit 编辑用户
     * @apiGroup 补充接口-幸运树游戏
     *
     * @apiParam {Int} id 主键id
     * @apiParam {Int} user_code 用户编号
     * @apiParam {String} expired_time 过期时间
     * @apiParam {String} pool_config 奖池id，多个用逗号,连接
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function edit(Request $request)
    {
        $id = $request->id;
        $userCode = $request->user_code; //用户编号
        $expiredTime = $request->expired_time; //过期时间
        $poolConfig = $request->pool_config;

        $userPool = app('model_independent_pool_user')
            ->select('id')->where('id', $id)->first();
        if (empty($userPool)) {
            throw new BasicException(10001);
        }

        $userId = app('model_user_data')->where('user_code', $userCode)->value('user_id');
        if (!$userId) {
            throw new BasicException(0, '用户不存在');
        }
        $independent_user = app('model_independent_pool_user')
            ->where(['user_id' => $userId])
            ->where('id', '<>', $id)
            ->first();
        if (isset($independent_user->status) && $independent_user->status == 1) {
            throw new BasicException(0, '用户已有特殊独立奖池');
        }

        if ($expiredTime <= date('Y-m-d H:i:s')) {
            throw new BasicException(0, '过期时间必须大于当前时间');
        }

        if (substr($poolConfig, -1, 1) == ',') {
            $poolConfig = substr($poolConfig, 0, -1);
        }
        $res = app('model_independent_pool_user')
            ->where('id', $id)
            ->update(['user_id' => $userId, 'expired_time' => strtotime($expiredTime), 'pool_config' => $poolConfig]);
        if ($res) {
            return Response::sendData([]);
        } else {
            throw new BasicException(0, '修改失败');
        }
    }

    /**
     * @api {Delete} /independentPoolUser/del 删除用户
     * @apiGroup 补充接口-幸运树游戏
     *
     * @apiParam {String} ids 主键id，多个用英文下逗号连接
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function del(Request $request)
    {

        $ids = $request->ids;
        $ids = str_replace('"', '', $ids);
        $ids = str_replace('\'', '', $ids);
        $ids = str_replace(' ', '', $ids);
        $ids = explode(',', $ids);

        DB::beginTransaction();
        try {
            foreach ($ids as $id) {
                if ($id) {
                    $userPool = app('model_independent_pool_user')
                        ->select('id', 'user_id')->where('id', $id)->first();
                    if (empty($userPool)) {
                        DB::rollBack();
                        throw new BasicException(10001);
                    }

                    app('model_independent_pool_user')->where(['id' => $id])->update(['status' => 0]);
                    app('model_independent_pool_user_detail')->where(['user_id' => $userPool->user_id])->delete();
                }
            }
            DB::commit();
            return Response::sendData([]);
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, '删除失败');
        }
    }
}